<template>
  <div class="scan-qrcode-components">

    <canvas id="image"></canvas>

    <input
      type="file"
      name=""
      @change="onFileChange"
      accept="image/*"
      capture="environment" >
    
    <p>
      <span>code: </span>
      <a :href="code" target="_blank">
        <strong>{{ code }}</strong>
      </a>
    </p>
    <footer style="height: 200px"></footer>
  </div>
</template>

<script>
import jsQR from 'jsqr'

export default {

  data () {
    const options = [
      { text: "rear camera (default)", value: "environment" },
      { text: "front camera", value: "user" },
      { text: "force file dialog", value: false },
    ]

    return {
      result: '',
      options,
      code: '',
      selected: options[0],
      MAX_IMAGE_SIZE: 1000,
    }
  },

  methods: {
    onDecode (result) {
      result.then(res => {
        console.log(res)
        alert(res.content + '???????????' + res.location)
        // this.result = result
      })
    },
    async onFileChange(event) {
      const file = event.target.files[0]
      const image = await this.getFileSize(file)
      const { width, height } = this.resizeImage(image)
      const imageData = this.getImageData(image)

      console.log(imageData)
      const result = jsQR(imageData, width, height)
      this.code = result.data

    },
    getFileSize(file) {
      const url = window.URL || window.webkitURL;
      const img = new Image();              //手动创建一个Image对象
      img.src = url.createObjectURL(file);//创建Image的对象的url
      return new Promise(resolve => {
        img.onload = function () {
          resolve(img)
        }
      })
    },
    getImageData(image) {
      // const canvas = document.createElement('canvas')
      const canvas = document.getElementById('image')
      const { width, height } = this.resizeImage(image)
      canvas.width = width
      canvas.height = height
      const context = canvas.getContext('2d')
      context.drawImage(image, 0, 0, width, height)
      const imageData = context.getImageData(0, 0, canvas.width, canvas.height)
      return imageData.data
    },
    resizeImage(image) {
      const size = { width: image.width, height: image.height }
      if (image.width <= this.MAX_IMAGE_SIZE && image.height <= this.MAX_IMAGE_SIZE) {
        return size
      } else {
        const max = image.width > image.height ? 'width' : 'height'
        const min = max === 'width' ? 'height' : 'width'
        size[max] = this.MAX_IMAGE_SIZE
        size[min] = image[min] * size[max] / image[max]
      }
      return size
    }
  }
}
</script>

<style scoped>
.error {
  font-weight: bold;
  color: red;
}

</style>